﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.Managers;
using Model;
using System.Windows.Input;
using MyAdressBookWPF.Helpers;
using System.Windows.Controls;
using System.Windows;

namespace MyAdressBookWPF.ViewModel
{
    class UserRegisterViewModel : ViewModelBase
    {
        #region private Fields
        private MainWindowViewModel _window;
        private string _userName;
        private UserDataManager _userDataManager;
        private ICommand _registerCommand;

        #endregion

        #region Constructors

        public UserRegisterViewModel(MainWindowViewModel window)
        {
            _window = window;
        }
        #endregion

        #region Public Properties

        public string UserName
        {
            get { return _userName; }
            set 
            { 
                _userName = value;
                OnPropertyChanged("UserName");
            }
        }

        public ICommand RegisterCommand
        {
            get
            {
                if (_registerCommand == null)
                {
                    RegisterCommand = new Command(ExecuteRegisterCommand);
                }
                return _registerCommand;
            }
            set
            {
                _registerCommand = value;
            }
        }
        #endregion

        #region Private methods

        public void ExecuteRegisterCommand(Object parameter)
        {
            var passwordBox = parameter as PasswordBox;
            var password = passwordBox.Password;

            if (VerifyUserName(_userName))
            {
                UserManager.CreateNewUser(_userName, password);
                if (UserManager.CheckUserConnexion(_userName, password, out _userDataManager))
                {
                    _window.CurrentViewModel = new ContactViewModel(_userDataManager);
                }
            }
            else
            {
                MessageBox.Show("This login is not avalaible");
            }
        }

        private bool VerifyUserName(string userName)
        {
            var allUserList = UserManager.GetAllUser();
            var userlist = (from u in allUserList
                            where u.UserName == userName
                            select u).ToList();

            if (userlist.Count == 0)
                return true;
            else
                return false;
        }
        #endregion
    }
}
